package top.huntwolf.admin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.exception.ServiceException;
import top.huntwolf.admin.pojo.Subject;
import top.huntwolf.admin.pojo.excel.SubjectExcelData;
import top.huntwolf.admin.service.SubjectService;


import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<SubjectExcelData> {

    private SubjectService subjectService;

    public SubjectExcelListener() {
    }


    // 传递subjectService过来操作数据库
    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    // 每读一行都会执行该方法
    @Override
    public void invoke(SubjectExcelData subjectExcelData, AnalysisContext analysisContext) {
        if (subjectExcelData == null) {
            throw new ServiceException(CodeMsg.READ_EXCEL_ERROR);
        }
        // 添加一级分类
        Subject oneSubject = this.existOneSubjectName(subjectExcelData.getOneSubjectName());
        // 为空才进行下续操作
        if (oneSubject == null) {
            oneSubject = new Subject();
            oneSubject.setParentId(0);
            oneSubject.setSort(0);
            oneSubject.setTitle(subjectExcelData.getOneSubjectName());

            this.subjectService.save(oneSubject);
            oneSubject = subjectService.findSubjectByTitle(oneSubject.getTitle());
        }

        // 获取一级分类的pid
        Integer pid = oneSubject.getId();

        // 添加二级分类
        Subject twoSubject = this.existTwoSubjectName(subjectExcelData.getTwoSubjectName(), pid);
        if (twoSubject == null) {
            twoSubject = new Subject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectExcelData.getTwoSubjectName());
            twoSubject.setSort(0);
            this.subjectService.save(twoSubject);
        }

    }

    // 读取表头
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
//        System.out.println("表头信息：" + headMap);
    }

    // 全部读取完成后才会执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //    判断一级分类是否重复
    private Subject existOneSubjectName(String title) {
        Subject firstSubject = subjectService.existSubject(title,0);
        return firstSubject;
    }

    private Subject existTwoSubjectName(String title, Integer pid) {

        Subject secondSubject = subjectService.existSubject(title,pid);
        return secondSubject;
    }

}
